import { Message, Tabs } from '@arco-design/web-react';
import TabPane from '@arco-design/web-react/es/Tabs/tab-pane';
import { useEffect, useState } from 'react';
import { ValidateRule } from '../../../types';
import DetailModal from '../../../components/detailModal';
import LoadingMask from '../../../components/loadingMask';
import { flowKTOG } from '../../../utils/utils';
import { apiGetCardPackDetailListByCardId, apiBuyPackOrder } from './api';

interface Props {
  cardId: number;
  iccid: string;
  onCancel: (update?: boolean) => void;
}

type Option = { label: string; value: number; isBasePackage: boolean; salePrice: string };


;

export default function BuyPackDetailDialog({ cardId, iccid, onCancel }: Props) {
  // 套餐列表
  const [packDetailList, setPackDetailList] = useState<Option[]>([]);
  // 套餐列表
  const [packList, setPackList] = useState<Option[]>([]);
  const [activeTab, setActiveTab] = useState('0');
  const [atIndex, setatIndex] = useState('');
  useEffect(() => {
    loadList();

  }, []); //eslint-disable-line

  useEffect(() => {
    getShowDetailList(packDetailList || [])
    setatIndex('')
  }, [activeTab,packDetailList]); // eslint-disable-line
  function getShowDetailList(rows: any) {
    const data = rows?.filter((item: any) => {
      if (activeTab === '0') {
        return item.packageType === 0 && item.prestoreType === 0
      } else if (activeTab === '1') {
        return item.packageType == 0 && item.prestoreType != 0
      } else {
        return item.packageType !== 0
      }
    })
    setPackList(data)
  }
  // 获取套餐详情列表
  async function loadList() {
    try {
      let res = await apiGetCardPackDetailListByCardId({ iccid: iccid });
      let data = res.data;
      if (data.code === 200) {
        setPackDetailList(data.data);
        getShowDetailList(data.data)
      } else {
        setPackDetailList([]);
        Message.warning(data.msg ?? '获取套餐列表失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '获取套餐列表失败');
    }
  }
  async function handleConfirm() {

    if (!atIndex) {
      return Message.warning('请选择套餐');
    }

    const obj:any = {
      packageId: atIndex,
      autoRenewalPackageId: atIndex,
      buyType: activeTab,
      cardId:cardId,
      createBy:iccid
    };
    if (activeTab !== '2') {
      obj.autoRenewalStatus = activeTab === '2' ? 0 : 1;
    }
    try {
      LoadingMask.show('正在购买...');
      let res = await apiBuyPackOrder(obj);
      let data = res.data;
      if (data.code === 200) {
        Message.success('购买成功');
        onCancel(true);
      } else {
        Message.warning(data.msg ?? '购买失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '购买失败');
    } finally {
      LoadingMask.hide();
    }
  }




  return (
    <DetailModal
      className="w-450"
      title={`手动订购【${iccid}】`}
      show
      onCancel={() => onCancel()}
      onConfirm={handleConfirm}
    >
      <Tabs
        key="card"
        className="tab-card mb-20"
        onChange={(v) => {
          setActiveTab(v);

        }}
      >
        <TabPane key="0" title="本月套餐"></TabPane>
        <TabPane key="1" title="次月套餐"></TabPane>
        <TabPane key="2" title="加油包"></TabPane>
      </Tabs>

      {
        <div className="mealList mealListhide">
          {
            packList?.map((item: any) => {
              return <div className={atIndex == item.id ? 'item seItem' : 'item'} onClick={() => setatIndex(item.id)}>
                <div className="image">{flowKTOG(item.flow || 0)}G</div>
                <div className="mealFlow">
                  <div className="" style={{whiteSpace: 'pre-line'}}>{item.packageName?.replace('（','\n（')}</div>

                </div>
                <div>
                  <div className="flowText">通用流量</div>
                </div>
                <div className="t3">￥{item.saleFace}</div>
              </div>
            })
          }

          <br />
          {/* <div class="btnBox" v-if="uData2.length">
          <button class="btn dbtn" @click="mealClick" type="default">
            订购
          </button>
        </div> */}
        </div>
      }
    </DetailModal>
  );
}
